y<template>
  <div class="category-list">
    <!-- 操作按钮 -->
    <!-- <el-button type="primary" @click="handleAdd">添加分类</el-button> -->

    <div style="margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center;">
      <el-button type="primary" @click="handleAdd">添加分类</el-button>

      <div class="search-bar">
        <el-input v-model="searchKeyword" placeholder="请输入分类名称" style="width: 200px;" />
        <el-button type="primary" @click="handleSearch" style="margin-left: 10px;">查询</el-button>
        <el-button @click="resetSearch" style="margin-left: 10px;">重置</el-button>
      </div>
    </div>
    <!-- 分类表格 -->
    <el-table :data="tableData" border style="width: 100%; margin-top: 20px;" row-key="id">
      <el-table-column prop="categoryName" label="分类名称"></el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" layout="total, prev, pager, next" :total="total">
    </el-pagination>

    <!-- 新增分类对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增分类" width="500px">
      <el-form :model="addForm" label-width="100px">
        <el-form-item label="分类名称">
          <el-input v-model="addForm.name" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddCategory">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑分类对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑分类" width="500px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="分类名称">
          <el-input v-model="editForm.categoryName" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditCategory">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { onMounted, ref, computed } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

axios.defaults.baseURL = "http://localhost:8080"

// 表格数据
//const tableData = ref([])

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)

// 所有分类数据
const allCategoryData = ref([])
const tableData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return allCategoryData.value.slice(start, end)
})
const total = computed(() => allCategoryData.value.length)

// 添加分类表单与对话框
const addDialogVisible = ref(false)
const addForm = ref({
  name: ''
})

// 编辑分类表单与对话框
const editDialogVisible = ref(false)
const editForm = ref({
  id: null,
  categoryName: ''
})

// 获取分类列表
const getCategoryList = async () => {
  try {
    const token = sessionStorage.getItem('token');
    const res = await axios.get('/categorys/list',
      {
        headers: {
          Authorization: `${token}`
        }
      }
    )
    if (res.data.code === 0) {
      allCategoryData.value = res.data.data
    } else {
      ElMessage.error('获取分类失败')
    }
  } catch (err) {
    ElMessage.error('加载分类失败')
    console.error(err)
  }
}
// 分页事件
const handleSizeChange = (val) => {
  pageSize.value = val
}
const handleCurrentChange = (val) => {
  currentPage.value = val
}
// 打开添加对话框
const handleAdd = () => {
  addForm.value = {
    name: ''
  }
  addDialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (index, row) => {
  editForm.value = { ...row }
  editDialogVisible.value = true
}

// 删除分类
const handleDelete = async (index, row) => {
  try {
    const confirmRes = await ElMessageBox.confirm(
      `确定删除分类 "${row.categoryName}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    if (confirmRes === 'confirm') {
      const token = sessionStorage.getItem('token');
      const res = await axios.delete(`/categorys/delete/${row.categoryId}`,
        {
          headers: {
            Authorization: `${token}`
          }
        }
      )
      if (res.data.code === 0) {
        ElMessage.success('删除成功')
        getCategoryList()
      } else {
        ElMessage.error(res.data.message || '删除失败')
      }
    }

  } catch (err) {
    if (err === 'cancel') {
      ElMessage.info('已取消删除');
    } else {
      console.error('删除地址失败:', err);
      ElMessage.error('删除地址失败');
    }
  }
}

// 提交新增分类
const submitAddCategory = async () => {
  const categoryName = addForm.value.name?.trim()

  try {
    const token = sessionStorage.getItem('token');
    const res = await axios.post('/categorys/add', {
      categoryName: categoryName
    },
      {
        headers: {
          Authorization: `${token}`
        }
      })

    if (res.data.code === 0) {
      ElMessage.success('添加成功')
      addDialogVisible.value = false
      getCategoryList()
    } else {
      ElMessage.error(res.data.message || '添加失败')
    }

  } catch (err) {
    ElMessage.error('网络错误，请稍后再试')
    console.error(err)
  }
}

// 提交编辑分类
const submitEditCategory = async () => {
  const categoryName = editForm.value.categoryName?.trim()
  const categoryId = editForm.value.categoryId

  if (!categoryName) {
    ElMessage.warning('分类名称不能为空')
    return
  }
  try {
    const category = {
      categoryId: categoryId,
      categoryName: categoryName
    }
    const token = sessionStorage.getItem('token');
    const res = await axios.put('/categorys/modfiy', category, {
      headers: {
        Authorization: `${token}`
      }
    })

    if (res.data.code === 0) {
      ElMessage.success('修改成功')
      editDialogVisible.value = false
      getCategoryList()
    } else {
      ElMessage.error(res.data.message || '修改失败')
    }

  } catch (err) {
    ElMessage.error('网络错误，请稍后再试')
    console.error(err)
  }
}

const searchKeyword = ref('');
// 搜索分类
const handleSearch = async () => {
  const keyword = searchKeyword.value.trim();

  if (!keyword) {
    // 如果搜索框为空，直接加载所有分类
    getCategoryList();
    ElMessage.info('正在显示全部分类');
    return;
  }

  try {
    const token = sessionStorage.getItem('token');
    const res = await axios.get('/categorys/search', {
      params: {
        categoryName: keyword
      },
      headers: {
        Authorization: `${token}`
      }
    });

    if (res.data.code === 0) {
      allCategoryData.value = res.data.data; // 更新为搜索结果
      currentPage.value = 1; // 回到第一页
      ElMessage.success(`找到 ${res.data.data.length} 条结果`);
    } else {
      ElMessage.error(res.data.message || '搜索失败');
    }
  } catch (err) {
    ElMessage.error('网络错误，请稍后再试');
    console.error(err);
  }
};
// 重置搜索
const resetSearch = () => {
  searchKeyword.value = ''; // 清空搜索关键词
  getCategoryList(); // 重新获取所有分类数据
}

onMounted(() => {
  getCategoryList()
})
</script>
<style scoped>
.category-list {
  padding: 20px;
}
</style>